<template>
  <div class="file-list-wrapper">
    <!-- 操作按钮 -->
    <el-header height="auto">
      <div style="padding:10px">
        <el-tabs tab-position="top" v-model="searchParams.storageId" @tab-change="selectStorage">
          <el-tab-pane v-for="item in storageList" :name="item.id" :label="item.storageName" :value="item.id"
                       :key="item.id"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="middle-wrapper">
        <!-- 面包屑导航栏 -->
        <AssetsBreadcrumb :folderList="breadcrumbList" @click="changeCurrentFolderId"></AssetsBreadcrumb>
      </div>
      <el-row :span="18" :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-dropdown class="upload-drop">
            <el-button
                plain
                type="primary"
                icon="upload">上传</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button plain type="primary" icon="Files"  @click="openDialog('addAssetsDialog')"
                             class="dropdown-btn">上传文件
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button plain type="primary" icon="Folder" @click="handleUploadFileBtnClick(2)"
                             class="dropdown-btn">上传文件夹
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button plain type="primary" icon="Rank" @click="handleUploadFileBtnClick(3)" class="dropdown-btn">
                    拖拽上传
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>

        <el-col :span="1.5">
          <el-dropdown class="create-drop">
            <el-button
                plain
                type="primary"
                icon="FolderAdd"
                id="uploadFileId">新建
            </el-button>
            <template #dropdown>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="openFolderDialog">
                  <div class="img-text-wrapper"><img src="../../assets/images/file/dir.png"/> 新建文件夹</div>
                </el-dropdown-item>
                <el-dropdown-item divided @click.native="handleCreateFile('docx')">
                  <div class="img-text-wrapper"><img src="../../assets/images/file/file_word.svg"/>Word 文档</div>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleCreateFile('xlsx')">
                  <div class="img-text-wrapper">
                    <img src="../../assets/images/file/file_excel.svg"/>Excel 工作表
                  </div>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleCreateFile('pptx')">
                  <div class="img-text-wrapper">
                    <img src="../../assets/images/file/file_ppt.svg"/>PPT 演示文稿
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
        <el-col :span="1.5">
          <el-dropdown v-show="showBatchOperation">
            <el-button plain size="mini" type="primary" icon="FolderAdd" id="uploadFileId">批量操作</el-button>
            <template #dropdown>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button size="mini" plain type="danger" icon="Delete" @click="handleBatchDeleteBtnClick"
                             class="dropdown-btn">删除
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button size="mini" plain type="warning" icon="Rank" @click="handleBatchMoveBtnClick"
                             class="dropdown-btn">移动
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleCreateFile('xlsx')">
                  <el-button plain size="mini" type="primary" icon="Download" @click="handleBatchDownloadBtnClick"
                             class="dropdown-btn">下载
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleCreateFile('pptx')">
                  <el-button plain size="mini" type="primary" icon="Share" @click="handleBatchShareBtnClick"
                             class="dropdown-btn">分享
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleCreateFile('pptx')">
                  <el-button plain size="mini" type="primary" icon="Management" @click="handleBatchShareBtnClick"
                             class="dropdown-btn">可见范围
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>

        <el-col :span="1.5">
          <el-input
              v-model="searchParams.title"
              placeholder="输入文件名称"
              suffix-icon="search"
              size="mini"
              maxlength="255"
              :clearable="true"
              @change="showFileList"
              @clear="showFileList"
              @keyup.enter.native="showFileList">
          </el-input>
        </el-col>
        <el-col :span="1.5">
          <el-select v-model="searchParams.types" multiple clearable collapse-tags placeholder="素材类型"
                     style="width: 240px" @change="showFileList">
            <el-option v-for="item in assetsTypes" :key="item.type" :label="item.name" :value="item.type"/>
          </el-select>
        </el-col>

        <el-col :span="1.5" style="margin-left: auto">
          <!-- 批量操作 -->
          <el-tooltip class="item" effect="dark" content="取消批量操作" placement="top" v-if="showBatchOperation">
            <el-button circle icon="Close" @click="cancelSelectedRows"/>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button circle icon="Refresh" @click="resetSearchForm"/>
          </el-tooltip>
          <!-- 操作栏收纳 -->
          <el-popover placement="bottom" trigger="hover">
            <template #reference>
              <el-button circle icon="Setting" @click="changeOperatePopoverVisible"></el-button>
            </template>
            <!-- 选择表格列 -->
            <SelectColumn></SelectColumn>
            <!-- 文件展示模式 -->
            <div class="change-file-model">
              <div class="title">查看模式</div>
              <el-radio-group v-model="fileGroupLable" size="mini" @change="handleFileDisplayModelChange">
                <el-radio-button label="0">
                  <el-icon>
                    <List></List>
                  </el-icon>
                  列表
                </el-radio-button>
                <el-radio-button label="1">
                  <el-icon>
                    <Grid></Grid>
                  </el-icon>
                  网格
                </el-radio-button>
                <el-radio-button label="2">
                  <el-icon>
                    <Calendar></Calendar>
                  </el-icon>
                  时间线
                </el-radio-button>
              </el-radio-group>
            </div>
            <el-divider class="split-line"></el-divider>
            <!-- 图标大小调整 -->
            <div class="change-grid-size">
              <div class="title">调整图标大小</div>
              <el-slider v-model="gridSize" :min="20" :max="150" :step="10" :format-tooltip="formatTooltip"></el-slider>
            </div>
          </el-popover>
        </el-col>
      </el-row>
    </el-header>
    <AddAssetsDialog :visible="dialogSwitchList.addAssetsDialog"
                     :folderIds="breadcrumbList"
                     :storageId="searchParams.storageId"
                     @reloadList="showFileList"></AddAssetsDialog>
    <FolderDialog :folderId="searchParams.folderId" :storageId="searchParams.storageId" :obj="folderDialog.currentFolder" :visiable="folderDialog.open" @closeDialog="closeFolderDialog"></FolderDialog>
    <PreviewDialog :visiable="dialogSwitchList.previewAssetsDialog" :previewId="datas.previewId"></PreviewDialog>
    <!-- 文件列表-表格模式 -->
    <FileTable
        :fileType="fileType"
        :filePath="filePath"
        :fileList="fileData"
        :loading.sync="loading"
        @getTableDataByType="showTables"
        @click.native.right="handleClickRight"
        @onDeleteAssets="removeAssets"
        @onUpdateAssets="openFolderDialog"
        @onSelectedRows="onSelectedRows"
        @onClickFolder="onClickFolder"
        @onPreviewAssets="previewAssets"
    ></FileTable>
    <!-- 文件列表-网格模式 -->
    <FileGrid
        :fileType="fileType"
        :filePath="filePath"
        :fileList="fileData"
        :loading="loading"
        v-if="false"
        @getTableDataByType="getTableDataByType"
        @click.native.right="handleClickRight"
    ></FileGrid>
    <!-- 图片-时间线模式 -->
    <FileTimeLine
        class="image-model"
        :fileList="fileData"
        :loading.sync="loading"
        v-if="false"
        @getTableDataByType="getTableDataByType"
        @click.native.right="handleClickRight"
    ></FileTimeLine>
    <div class="pagination-wrapper">
      <div class="current-page-count">当前页{{ fileData.length }}条</div>
      <el-pagination
          :current-page="searchParams.curPage"
          :page-size="searchParams.pageSize"
          :total="searchParams.total"
          :page-sizes="[10, 20, 50, 200]"
          :layout="'sizes, total, prev, pager, next'"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup name="FileList">
import FileTable from '@/components/Assets/FileTable.vue'
import FileGrid from '@/components/Assets/FileGrid.vue'
import FileTimeLine from '@/components/Assets/FileTimeLine.vue'
import AssetsBreadcrumb from '@/components/Assets/AssetsBreadcrumb.vue'
import AddAssetsDialog from './Dialog/AddAssetsDialog.vue'
import FolderDialog from './Dialog/FolderDialog'
import {ref, computed} from 'vue'
import {
  listAssets,
  delAssets,
  assetsTypeList,
  delFolder,
  getDownloadUrl
} from '../../api/knowledge/assets.js'
import {listStorage} from '@/api/knowledge/storage.js'
import PreviewDialog from "./Dialog/PreviewDialog.vue";

const route = useRoute();

let {proxy} = getCurrentInstance();
const storageList = ref([]);
const assetsTypes = ref({})
const searchParams = reactive({
  title: "",
  type: null,
  types: [],
  folderId: -1,
  storageId: null,
  curPage: 1,
  pageSize:20
})
const loading = ref(true);
const fileData = ref([]);

// 弹窗开关
const dialogSwitchList = reactive({
  addAssetsDialog: false,
  previewAssetsDialog: false
})

const folderDialog = reactive({
  open: false,
  currentFolder:{}
})

const datas = reactive({
  previewId: null
});

const selectedRows = ref([]);
const breadcrumbList = ref([{
  title: '全部',
  id: -1
}])
const showBatchOperation = computed(() => {
  return selectedRows.value && selectedRows.value.length > 0;
})

watch(searchParams, () => {
  showFileList();
})

function openDialog(dialog){
  dialogSwitchList[dialog] = !dialogSwitchList[dialog]
}

function resetSearchForm() {
  searchParams.title = "";
  searchParams.type = "";
  searchParams.types = [];
  showFileList();
}

function onClickFolder(row) {
  breadcrumbList.value.push({
    title: row.title,
    id: row.id
  })
  searchParams.folderId = row.id
}

function changeCurrentFolderId(folderId) {
  searchParams.folderId = folderId
  let index = 0;
  for(let i=0; i< breadcrumbList.value.length; i++){
    if (folderId === breadcrumbList.value[i].id) {
      index = i
      break
    }
  }
  if (breadcrumbList.value.length > index + 1) {
    breadcrumbList.value.splice(index+1, breadcrumbList.value.length - index-1)
  }
}

function closeFolderDialog(){
  showFileList()
}

function cancelSelectedRows() {
  selectedRows.value = []
}

function onSelectedRows(rows) {
  selectedRows.value = rows
}

function openFolderDialog(data) {
  folderDialog.open = !folderDialog.open;
  if(data && data.id){
    data.permission = parsePermission(data.permission)
    folderDialog.currentFolder = data
  }else{
    folderDialog.currentFolder = {}
  }
}

function previewAssets(data) {
  dialogSwitchList.previewAssetsDialog = !dialogSwitchList.previewAssetsDialog
  datas.previewId = data.id
}

function parsePermission(permissionStr) {
  if (permissionStr) {
    try {
      return JSON.parse(permissionStr)
    } catch {

    }
  }
  return {
    value: 'invisible'
  }
}

//删除素材
function removeAssets(data) {
  if (data.objectType === 'folder') {
    loading.value = true
    delFolder(data.id).then(res => {
      if (res.code === 200) {
        loading.value = false
        proxy.$modal.msgSuccess("删除成功");
        showFileList()
      } else {
        proxy.$modal.msgError("删除失败")
      }
    })
  }
  if (data.objectType === 'assets') {
    loading.value = true
    delAssets(data.id).then(res => {
      if (res.code === 200) {
        loading.value = false
        proxy.$modal.msgSuccess("删除成功");
        showFileList()
      } else {
        proxy.$modal.msgError("删除失败")
      }
    })
  }
}

function getAssetsTypes() {
  assetsTypeList().then((res) => {
    if (res.success) {
      assetsTypes.value = res.data
      loading.value = false
    } else {
      proxy.$modal.msgError(res.message)
    }
  })
}

function getStorageList() {
  listStorage().then((res) => {
    if (res.success) {
      storageList.value = res.data
      loading.value = false
      searchParams.storageId = res.data.length > 0 ? res.data[0].id : -1
    } else {
      proxy.$modal.msgError(res.message)
    }
  })
}

/**
 * 文件展示区域的空白处右键事件
 * @param {Document} event 右键事件对象
 */
function handleClickRight(event) {
  event.preventDefault()
  // 只有在全部页面才可以进行以下操作
  if (![6, 8].includes(fileType)) {
    proxy.$openBox
        .contextMenu({
          selectedFile: undefined,
          domEvent: event,
          serviceEl: this
        })
        .then((res) => {
          if (res === 'confirm') {
            showFileList() //  刷新文件列表
            storageStore.refreshStorage() //  刷新存储容量
          }
        })
  }
}


function showFileList() {
  loading.value = true;
  listAssets(searchParams).then((res) => {
    if (res.success) {
      fileData.value = res.data.list
      searchParams.total = Number(res.data.total)
      loading.value = false
    } else {
      proxy.$modal.msgError(res.message)
    }
  })
}

/**
 * 表格数据获取相关事件 | 分页组件 | 当前页码改变
 */
function handleCurrentChange(currentPage) {
  searchParams.curPage = currentPage
}

/**
 * 表格数据获取相关事件 | 分页组件 | 页大小改变时
 */
function handleSizeChange(pageCount) {
  searchParams.pageSize = pageCount
}

/**
 * 表格数据获取相关事件 | 获取回收站文件列表
 */
function showFileRecovery() {
  listAssets().then((res) => {
    if (res.success) {
      fileData.value = res.data.list
      loading.value = false
    } else {
      proxy.$modal.msgError(res.message)
    }
  })
}

/**
 * 表格数据获取相关事件 | 获取我的分享列表
 */
function showMyShareFile() {
  let data = {
    shareFilePath: filePath,
    shareBatchNum: proxy.$route.query.shareBatchNum,
    currentPage: pageData.currentPage,
    pageCount: pageData.pageCount
  }
  listAssets(data).then((res) => {
    if (res.success) {
      fileData.value = res.data.list
      pageData.total = Number(res.total)
      loading.value = false
    } else {
      proxy.$modal.msgError(res.message)
    }
  })
}


/**
 * 获取搜索文件结果列表
 * @param {string} fileName 文件名称
 */
function getSearchFileList(fileName) {
  loading.value = true
  searchFile({
    currentPage: pageData.currentPage,
    pageCount: pageData.pageCount,
    fileName: fileName
  }).then((res) => {
    loading.value = false
    if (res.success) {
      fileData.value = res.data.list.map((item) => {
        return {
          ...item,
          highlightFields: item.highLight.fileName[0]
        }
      })
      pageData.total = res.data.totalHits
    } else {
      proxy.$modal.msgError(res.message)
    }
  })
}

function selectStorage (storageId) {
  searchParams.storageId = storageId
  searchParams.folderId = -1
  breadcrumbList.value = breadcrumbList.value.slice(0,1)
}

onMounted(() => {
  getAssetsTypes()
  getStorageList()
})
</script>

<style lang="scss" scoped>
@import '../../assets/styles/variables.module.scss';
@import '../../assets/styles/mixin.scss';

.file-list-wrapper {
  .middle-wrapper {
    margin-bottom: 8px;
  }

  .pagination-wrapper {
    position: relative;
    border-top: 1px solid $BorderBase;
    height: 44px;
    line-height: 44px;
    text-align: center;

    .current-page-count {
      position: absolute;
      left: 16px;
      height: 32px;
      line-height: 32px;
      font-size: 13px;
      color: $RegularText;
    }
  }
}

.operation-menu-wrapper.file-type-6 {
  margin: 8px 0;
  justify-content: flex-end;
}

.operation-menu-wrapper {
  padding: 16px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .create-operate-group {
    .upload-drop {
      float: left;

      .el-button {
        border-radius: 4px 0 0 4px;
      }
    }
  }

  .batch-operate-group {
    flex: 1;
  }

  .select-file-input {
    margin-right: 8px;
    width: 250px;

    .el-icon-search {
      cursor: pointer;
      font-size: 16px;

      &:hover {
        color: $primaryColor;
      }
    }
  }

  .batch-icon,
  .model-icon {
    margin-right: 8px;

    &:last-of-type {
      margin-right: 0;
    }
  }

  .model-icon.active {
    color: $primaryColor;
  }

  .refresh-icon, .batch-icon, .model-icon, .setting-icon {
    font-size: 20px;
    cursor: pointer;
    color: $SecondaryText;

    &:hover {
      color: $primaryColor;
    }
  }

  .batch-icon.active {
    color: $primaryColor;
  }
}

.split-line {
  margin: 8px 0;
}

.img-text-wrapper {
  display: flex;
  align-items: center;

  img {
    margin-right: 4px;
    height: 24px;
  }
}

.dropdown-btn {
  width: 120px;
}
</style>
